<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      body {
        background-color: black;
      }
      .wrap {
        position: relative;
        width: 1000px;
        height: 500px;
        border: 10px solid pink;
        margin: 100px auto;
      }
      .box {
        width: 100px;
        height: 100px;
        /* 圆 */
        border-radius: 50%;
        background-color: white;
        position: absolute;
        top: 0;
        left: 0;
      }
    </style>
  </head>
  <body>
    <div class="wrap">
      <div class="box"></div>
    </div>
    <script>
      let wrap = document.getElementsByClassName("wrap")[0];
      let box = document.getElementsByClassName("box")[0];
      //获取运动范围
      var maxw = wrap.clientWidth - box.clientWidth;
      var maxh = wrap.clientHeight - box.clientHeight;
      console.log(maxh, maxw);
      //初始值
      var x = 0;
      var y = 0;
      var speedX = 5;
      var speedY = 6;
      //使用定时器
      setInterval(function () {
        x += speedX;
        y += speedY;
        if (x > maxw) {
          speedX *= -1;
        } else if (x < 0) {
          speedX *= -1;
        }

        if (y > maxh) {
          speedY *= -1;
        } else if (y < 0) {
          speedY *= -1;
        }
        //赋值
        box.style.left = x + "px";
        box.style.top = y + "px";
      }, 20);
    </script>
  </body>
</html>
